var gotoLineAnaFaultInfo;
require(['highcharts', 'reportCommon'], function () {
    var lineId, lineName, titleStr = "", dateType = "02";

    function lineChange(event, treeId, treeNode) {
        if (treeNode.type === 'LINE') {
            lineId = treeNode.id;
            lineName = treeNode.name;
            clear();
            //标题时间
            titleStr = chartTitle(dateType);
            getLineAnaFaultIdx(lineId, dateType);
            getLineAnaFaultTrend(lineId, dateType);
            getLineFaultRankInfo(lineId, dateType);
            getLineUnFaultRankInfo(lineId, dateType);
        } else {
            $.messager.alert("提示", "请选择线路进行查看。");
        }
    }

    //左侧树
    commonFun.leftTreeNodeClickObj['lineAnaFaultInfo'] = lineChange;

    //顶部日期类型
    $(".time-select a").click(function () {
        if (lineId) {
            dateType = $(this).attr('val');
            clear();
            //标题时间
            titleStr = chartTitle(dateType);
            $(this).addClass("active");
            $(this).siblings().removeClass("active");
            getLineAnaFaultIdx(lineId, dateType);
            getLineAnaFaultTrend(lineId, dateType);
            getLineFaultRankInfo(lineId, dateType);
            getLineUnFaultRankInfo(lineId, dateType);
        }
    });

    //清空历史记录
    function clear() {
        $("p").html("");
        $("span").html("");
    }


    //故障发生数、线路平均数
    function getLineAnaFaultIdx(lineId, dateType) {
        $.ajaxExt({
            url: "/lineAna/getLineAnaFaultIdx.htm",
            data: {'lineId': lineId, 'dateType': dateType}
        }).done(function (data) {
            $("#faultCntPer").removeClass();
            $("#lineAvgCntPer").removeClass();
            $("#faultRankPer").removeClass();
            $(data).each(function (i, item) {
                if (item.idxType == "050801") {
                    $("#faultCnt").html(item.idxValue);
                    var per = item.idxmomperstr;
                    $("#faultCntPer").html(per);
                    if (per.indexOf("-") != 0) {
                        $("#faultCntPer").addClass("icon-arrow-up");
                    } else {
                        $("#faultCntPer").addClass("icon-arrow-up");
                        $("#faultCntPer").addClass("icon-arrow-down");
                    }
                } else if (item.idxType == "050802") {
                    $("#lineAvgCnt").html(item.idxValue);
                    var per = item.idxmomperstr;
                    $("#lineAvgCntPer").html(per);
                    if (per.indexOf("-") != 0) {
                        $("#lineAvgCntPer").addClass("icon-arrow-up");
                    } else {
                        $("#lineAvgCntPer").addClass("icon-arrow-up");
                        $("#lineAvgCntPer").addClass("icon-arrow-down");
                    }
                }
            });
        });
    }

    //故障趋势
    function getLineAnaFaultTrend(lineId, dateType) {
        $.ajaxExt({
            url: "/lineAna/getLineAnaFaultTrend.htm",
            data: {'lineId': lineId, 'dateType': dateType}
        }).done(function (data) {
            if (data && data.length > 0) {
            	console.info(data);
                //每日故障数据
                var series = [], category = [],
                    tmpDate = data[0].REPORT_DATE;
                for (var i = 0; i < data.length; i++) {
                    if (data[i].REPORT_DATE == tmpDate) {
                    	series.push({"name": data[i].TREND_VAL1, "color": data[i].colorCode, data: []});
//                    	if(data[i].TREND_VAL1=='BMS故障'){
//                        	series.push({"name": data[i].TREND_VAL1,"color": "#F7A35C",data: []});
//                        }else if(data[i].TREND_VAL1=='DMC故障'){
//                        	series.push({"name": data[i].TREND_VAL1,"color": "#7CB5ED",data: []});
//                        }else if(data[i].TREND_VAL1=='电池故障'){
//                        	series.push({"name": data[i].TREND_VAL1,"color": "#424248",data: []});
//                        }else if(data[i].TREND_VAL1=='车身故障'){
//                        	series.push({"name": data[i].TREND_VAL1,"color": "#91ED7C",data: []});
//                        }
                    } else {
                        break;
                    }
                }
                for (var i = 0; i < data.length; i += series.length) {
                    xAxisDateFormat(dateType, category, data[i].REPORT_DATE);
                    for (var s = 0; s < series.length; s++) {
                        series[s].data.push(parseInt(data[i + s].TREND_VAL2));
                    }
                }
                $('#lineFaultData').highcharts({
                    chart: {
                        type: 'column'
                    },
                    title: {
                        text: "线路：" + lineName + ' ' + titleStr,
                        style: {
                            fontFamily: 'sans-serif',
                            fontSize: '14px'
                        }
                    },
                    xAxis: {
                        categories: category
                    },
                    yAxis: {
                        min: 0,
                        title: {
                            text: ''
                        },
                        stackLabels: {
                            enabled: true,
                            style: {
                                fontWeight: 'bold',
                                color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
                            }
                        }
                    },
                    credits: {
                        enabled: false
                    },
                    legend: {
                        align: 'center',
                        verticalAlign: 'bottom',
                        y: 20,
                        floating: true,
                        backgroundColor: (Highcharts.theme && Highcharts.theme.legendBackgroundColorSolid) || 'white',
                        borderColor: '#CCC',
                        shadow: false
                    },
                    tooltip: {
                        formatter: function () {
                            return '<b>' + this.x + '</b><br/>' +
                                this.series.name + ': ' + this.y + '<br/>' +
                                'Total: ' + this.point.stackTotal;
                        }
                    },
                    plotOptions: {
                        column: {
                            stacking: 'normal',
                        }
                    },
                    series: series
                });
            }
        });
    }

    //故障排名 饼图
    function getLineFaultRankInfo(lineId, dateType) {
        /*$('#trHtml').canGrid('reload', {
         params: {'lineId' : lineId,'dateType' : dateType}
         });*/
        $.ajaxExt({
            url: "/lineAna/getLineFaultRankInfo.htm",
            data: {'lineId': lineId, 'dateType': dateType}
        }).done(function (data) {
            var faultPct = [{type:'pie',data:[]}];
            trHtml = "<tr><th width='15%'>排名</th><th width='25%'>故障名称</th><th width='15%'>次数</th><th width='20%'>百分比</th></tr>";
            $(data).each(function (i, item) {
                if (item.IDX_TYPE == "051001") {
                    //故障排名
                    trHtml += "<tr><td><span class='rank-tip'>" + item.RANK_SN + "</span></td><td>" + item.RANK_VAL1 + "</td><td>" + item.RANK_VAL2 + "</td><td>" + item.RANK_VAL3 + "</td></tr>";
                    //饼图
//                    console.info(item.RANK_VAL2);
//                    faultPct.push([item.RANK_VAL1, parseInt(item.RANK_VAL2) || 0]);
//                    if(item.RANK_VAL1=='BMS故障'){
//                    	faultPct[0].data.push({"name": item.RANK_VAL1,"color": "#F7A35C",y: parseInt(item.RANK_VAL2)});
//                    }else if(item.RANK_VAL1=='DMC故障'){
//                    	faultPct[0].data.push({"name": item.RANK_VAL1,"color": "#7CB5ED",y: parseInt(item.RANK_VAL2)});
//                    }else if(item.RANK_VAL1=='电池故障'){
//                    	faultPct[0].data.push({"name": item.RANK_VAL1,"color": "#424248",y: parseInt(item.RANK_VAL2)});
//                    }else if(item.RANK_VAL1=='车身故障'){
//                    	faultPct[0].data.push({"name": item.RANK_VAL1,"color": "#91ED7C",y: parseInt(item.RANK_VAL2)});
//                    }
                    faultPct[0].data.push({"name": item.RANK_VAL1,"color": item.colorCode, y: parseInt(item.RANK_VAL2)});
//                    faultPct[0].data.push({"name": item.RANK_VAL1, y: parseInt(item.RANK_VAL2)});
                }
            });
            $("#trHtml").html(trHtml);
            //饼图
            $("#faultPct").highcharts({
                chart: {
                	type:'pie',
                    plotBackgroundColor: null,
                    plotBorderWidth: null,
                    plotShadow: false
                },
                title: {
                    text: "线路：" + lineName + ' ' + titleStr,
                    style: {
                        fontFamily: 'sans-serif',
                        fontSize: '14px'
                    }
                },
//                colors:['#91ED7C','#F7A35C','#7CB5ED','#424248'],
                tooltip: {
                    pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
                },
                plotOptions: {
                    pie: {
                        allowPointSelect: true,
                        cursor: 'pointer',
                        dataLabels: {
                            enabled: true,
                            color: '#000000',
                            connectorColor: '#000000',
                            format: '<b>{point.name}</b>: {point.percentage:.1f} %'
                        }
                    }
                },
                credits: {
                    enabled: false
                },
                series: faultPct
            });
        });
    }

    //车辆故障排名
    function getLineUnFaultRankInfo(lineId, dateType) {
        $.ajaxExt({
            url: "/lineAna/getLineUnFaultRankInfo.htm",
            data: {'lineId': lineId, 'dateType': dateType}
        }).done(function (data) {
        	if(data){
        		var series = [], lic = [], lx = [], category = [], colors = [], lxArr = [], tmpCorlor = [];
        		var tmpVal = [];
        		$(data).each(function (i, item) {
        			lic.push(item.LIC_PLT_NO);
        			lx.push(item.RANK_VAL1);
        			colors.push(item.colorCode);
        			if(category.length == 0 || category.indexOf(item.LIC_PLT_NO) < 0){
                    	category.push(item.LIC_PLT_NO);
                    	tmpVal.push(parseInt(item.RANK_VAL3));
                    }else{
                    	var num = category.indexOf(item.LIC_PLT_NO);
                    	tmpVal[num] += parseInt(item.RANK_VAL3);
                    }
        		});
        		//bug原因:类型数组去重使用jQuery.unique()在火狐和IE中失效
//        		category = $.unique(lic);
//        		lxArr = $.unique(lx);
//        		colors = $.unique(colors);
        		
        		
                lxArr.push(lx[0]);
                tmpCorlor.push(colors[0]);
              //类别根据总数排名
                for(var i=0;i<tmpVal.length;i++){
                	for(var j=i+1;j<tmpVal.length;j++){
                		if(tmpVal[i] < tmpVal[j]){
                			var tmp = tmpVal[j];
                			tmpVal[j] = tmpVal[i];
                			tmpVal[i] = tmp;
                			
                			tmp = category[j];
                			category[j] = category[i];
                			category[i] = tmp;
                			
                		}
                	}
                }
                
                
                for(var i=1;i<lx.length;i++){
                	if(lxArr.indexOf(lx[i]) < 0){
                		lxArr.push(lx[i]);
                	}
                }
                for(var i=1;i<colors.length;i++){
                	if(tmpCorlor.indexOf(colors[i]) < 0){
                		tmpCorlor.push(colors[i]);
                	}
                }
                colors = tmpCorlor;
        		
        		for (var i = 0; i < lxArr.length; i++) {
        			var tmp = [];
        			for (var j = 0; j < category.length; j++) {
        				tmp.push(parseInt(0));
        			}
        			series.push({"name": lxArr[i], "color": colors[i], "data": tmp});
//        			series.push({"name": lxArr[i], "data": tmp});
//        			if(lxArr[i]=='BMS故障'){
//        				series.push({"name": lxArr[i],"color": "#F7A35C","data": tmp});
//        			}else if(lxArr[i]=='DMC故障'){
//        				series.push({"name": lxArr[i],"color": "#7CB5ED","data": tmp});
//        			}else if(lxArr[i]=='电池故障'){
//        				series.push({"name": lxArr[i],"color": "#424248","data": tmp});
//        			}else if(lxArr[i]=='车身故障'){
//        				series.push({"name": lxArr[i],"color": "#91ED7C","data": tmp});
//        			}
        		}
        		for (var k = 0; k < lxArr.length; k++) {//类型
        			for (var i = 0; i < category.length; i++) {//25 车
        				for (var j = 0; j < data.length; j++) {//42 数据
        					if (category[i] == data[j].LIC_PLT_NO && lxArr[k] == data[j].RANK_VAL1) {
	                        	if(data && data[j].RANK_VAL3)
	                        		series[k].data[i] = parseInt(data[j].RANK_VAL3);
	                        	else
	                        		series[k].data[i] = 0;
        					}
        				}
        			}
        		}
        		// 线路故障排名
        		$('#faultRankPct').highcharts({
        			chart: {
        				type: 'bar'
        			},
        			title: {
        				text: "线路：" + lineName + ' ' + titleStr,
        				style: {
        					fontFamily: 'sans-serif',
        					fontSize: '14px'
        				}
        			},
        			credits: {
        				enabled: false
        			},
        			xAxis: {
        				categories: category
        			},
        			yAxis: {
        				min: 0,
        				title: {
        					text: ''
        				}
        			},
        			legend: {
        				backgroundColor: '#FFFFFF',
        				reversed: true
        			},
        			plotOptions: {
        				series: {
        					stacking: 'normal'
        				}
        			},
        			series: series
        		});
        	}
        });

    }

    //如果左侧树有选择线路则直接查询该线路数据
    business.execFnByLeftTreeSelectNode('LINE', lineChange);

    gotoLineAnaFaultInfo=function(data){
        commonFun.showLeftTree(commonFun.lineTree);
        commonFun.setSelectedNodes(data.lineId);
        lineId = data.lineId;
        lineName = data.lineName;
        $("a[val='" + data.dateType + "']",".time-select").click();
    }
});